import { GlobalData } from '/store/state'
import { getServer } from '/store/mutations'
import { userApi } from '/api/user'

Page({
  data: {
    value: '' as number | string,
    type: 'wechat' as 'alipay' | 'wechat',
    account: '',
    wallet: {} as any,
    user: {} as any,
    min: 0 as number,
    lock: false,
  },
  async onLoad() {
    this.setData({
      wallet: GlobalData.wallet,
      min: +GlobalData.wallet.cash['min-amount'] / 100,
    })
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data
    this.setData({
      user,
      placeholder: `可提现${(user.wallet.balance / 100).toFixed(2)}元`,
    })
  },
  /** 提现金额 */
  inputMoney(e: WechatMiniprogram.Input) {
    const {
      detail: { value },
    } = e
    this.setData({
      value: +value,
    })
  },
  /** 全部提现 */
  selectAll() {
    this.setData({
      value: this.data.user.wallet.balance / 100,
    })
  },
  /** 提现类型 */
  chooseType() {
    wx.showActionSheet({
      itemList: ['支付宝提现', '微信提现'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.setData({
              type: 'alipay',
            })
            break
          case 1:
            this.setData({
              type: 'wechat',
            })
        }
      },
    })
  },
  /** 提现账户 */
  inputNum(e:WechatMiniprogram.Input) {
    const {
      detail: { value },
    } = e
    this.setData({
      account: value,
    })
  },
  /** 提现明细 */
  toDetail() {
    wx.navigateTo({
      url: '/mine/withdrawList/withdrawList',
    })
  },
  /** 提交 */
  async submit() {
    const { value, user, account, type, min, lock } = this.data
    if (lock) return
    if (+value * 100 > user.wallet.balance) {
      wx.showToast({
        title: `最多可提现${user.wallet.balance / 100}元`,
        icon: 'none',
      })
      return
    }
    if (value < min) {
      wx.showToast({
        title: `至少提现${min}元`,
        icon: 'none',
      })
      return
    }
    if (!account) {
      wx.showToast({
        title: `请输入提现账号`,
        icon: 'none',
      })

      return
    }
    this.setData({
      lock: true,
    })
    await userApi
      .postWithdraw({
        value: +value * 100,
        type,
        account,
      })
      .then(() => {
        wx.showToast({
          title: '提现成功',
          duration: 1000,
        })
        setTimeout(() => {
          wx.navigateBack({ delta: 1 })
        }, 1000)
      })
      .catch((error) => {
        wx.showToast({
          title: '提现失败!',
          icon: 'none',
          duration: 1000,
        })
        this.setData({
          lock: false,
        })
      })
  },
})
